<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;

/**
 * 工厂切换
 *
 * @icon fa fa-exchange
 * @remark 切换当前操作的工厂
 */
class FactorySwitch extends Backend
{
    /**
     * 工厂切换页面
     */
    public function index()
    {
        $factories = \app\admin\model\scanwork\Factory::where('status', 1)
            ->order('sort asc, id asc')
            ->select();
        
        $currentFactoryId = session('current_factory_id');
        
        $this->view->assign('factories', $factories);
        $this->view->assign('currentFactoryId', $currentFactoryId);
        
        return $this->view->fetch();
    }

    /**
     * 切换工厂
     */
    public function switch()
    {
        $factoryId = $this->request->post('factory_id');
        
        if (!$factoryId) {
            $this->error('请选择要切换的工厂');
        }
        
        // 检查工厂是否存在且用户有权限
        $factory = \app\admin\model\scanwork\Factory::get($factoryId);
        if (!$factory || $factory->status != 1) {
            $this->error('工厂不存在或已禁用');
        }
        
        // 检查用户是否有权限访问该工厂
        $hasPermission = \app\admin\model\scanwork\UserFactory::where([
            'user_id' => $this->auth->id,
            'factory_id' => $factoryId,
            'status' => 1
        ])->find();
        
        if (!$hasPermission) {
            $this->error('您没有权限访问该工厂');
        }
        
        // 设置当前工厂
        session('current_factory_id', $factoryId);
        
        $this->success('工厂切换成功', null, [
            'factory_id' => $factoryId,
            'factory_name' => $factory->name
        ]);
    }

    /**
     * 获取当前工厂信息
     */
    public function getCurrent()
    {
        $factoryId = session('current_factory_id');
        if (!$factoryId) {
            $this->error('未选择工厂');
        }
        
        $factory = \app\admin\model\scanwork\Factory::get($factoryId);
        if (!$factory) {
            $this->error('工厂不存在');
        }
        
        $this->success('', null, [
            'id' => $factory->id,
            'name' => $factory->name,
            'code' => $factory->code
        ]);
    }

    /**
     * 获取用户可访问的工厂列表
     */
    public function getList()
    {
        $userId = $this->auth->id;
        $factoryIds = \app\admin\model\scanwork\UserFactory::where('user_id', $userId)
            ->where('status', 1)
            ->column('factory_id');
        
        if (empty($factoryIds)) {
            $this->success('', null, []);
        }
        
        $factories = \app\admin\model\scanwork\Factory::where('id', 'in', $factoryIds)
            ->where('status', 1)
            ->order('sort asc, id asc')
            ->field('id,name,code')
            ->select();
        
        $this->success('', null, $factories);
    }
}
